package org.lex.tinyscript;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Properties;

import org.lex.tinyscript.utils.Loggers;

public class JavaLauncher {
	public static final String JVM_PATH = "jvmPath";
	public static final String WORKING_DIRECTORY = "workingDirectory";
	public static final String MAIN_CLASS = "mainClass";
	public static final String JVN_ARGS = "jvmArgs";
	public static final String APP_ARGS = "appArgs";

	private Properties props = null;

	public static JavaLauncher newInstance(File props) throws IOException {
		Properties p = new Properties();
		p.load(new FileInputStream(props));
		return new JavaLauncher(p);
	}

	public JavaLauncher(Properties args) {
		this.props = args;
	}

	public Properties getLaunchProperties() {
		return this.props;
	}

	public ProcessBuilder getProcessBuilder() throws TinyScriptException {
		ArrayList<String> cmds = new ArrayList<String>(props.size() * 2);
		// jvm path
		String jvmPath = this.props.getProperty(JVM_PATH, "java");
		cmds.add(jvmPath);
		// jvm args
		String jvmArgs = this.props.getProperty(JVN_ARGS, "");
		if (false == this.isEmpty(jvmArgs)) {
			cmds.add(jvmArgs);
		}
		// mainClass
		String mainClass = this.props.getProperty(MAIN_CLASS, "");
		if (true == this.isEmpty(mainClass)) {
			throw new TinyScriptException("Main Class name can't be null!");
		}
		cmds.add(mainClass);
		// app args
		String appArgs = this.props.getProperty(APP_ARGS, "");
		if (false == this.isEmpty(appArgs)) {
			cmds.add(appArgs);
		}
		Loggers.getLogger().info("launch java command: " + cmds);

		ProcessBuilder pb = new ProcessBuilder(cmds);
		String pwd = this.props.getProperty(WORKING_DIRECTORY, ".");
		Loggers.getLogger().info("startup dir: " + pwd);
		pb.directory(new File(pwd));
		return pb;
	}

	public String toString() {
		return this.props.toString();
	}

	private boolean isEmpty(String str) {
		return null == str || 0 == str.trim().length();
	}
}
